import yfinance as yf
import pandas as pd
import openpyxl

def donchian_channel(ticker, n=20):
    df = yf.download(ticker)
    df['20MA'] = df['Close'].rolling(window=n).mean()
    df['Up'] = df['20MA'] + 2*(df['Close'].rolling(window=n).std())
    df['Down'] = df['20MA'] - 2*(df['Close'].rolling(window=n).std())

    # 判断是否突破20日线
    df['Uptrend'] = df['Close'] > df['20MA']
    df['Downtrend'] = df['Close'] < df['20MA']

    upper = df[['Up']]
    upper = upper.rename(columns={'Up': '通道上轨'})
    lower = df[['Down']]
    lower = lower.rename(columns={'Down': '通道下轨'})
    head = df[['Open', 'High', 'Low', 'Close', '20MA', 'Uptrend', 'Downtrend']]
    head = head.rename(columns={'Open': '开盘价', 'High': '最高价', 'Low': '最低价', 'Close': '收盘价', '20MA': '20日均线', 'Uptrend': '是否突破20日线', 'Downtrend': '是否跌破20日线'})
    return upper, lower, head

storage_stocks_list = [2459, 300693, 300827, 300656, 300217, 300629, 300153, 2335, 601727, 603626, 601222, 601126, 2939, 2455];
for stockCode in storage_stocks_list:
    print(stockCode)
    # stockCode = "601919"
    dataArray = donchian_channel(str(stockCode)+".SS")
    print(dataArray[2])
    pd.DataFrame(dataArray[2]).to_csv(str(stockCode) + ".csv")


